﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Aandelendelen.Mail;
using Aandelendelen.Db;
using Aandelendelen.Obs;
using Aandelendelen.Security;

namespace Aandelendelen.Controls
{
	public partial class LoginControl : BaseUserControl
	{
		protected override void OnPostBack(object sender, EventArgs e)
		{
			if (this.Gebruikersnaam.Length > 0)
			{
				string newUrl;
				int index = this.HyperLink1.NavigateUrl.IndexOf("?uid=");
				if (index > 0)
					newUrl = this.HyperLink1.NavigateUrl.Substring(0, index);
				else
					newUrl = this.HyperLink1.NavigateUrl;

				this.HyperLink1.NavigateUrl = newUrl + "?uid=" + this.Gebruikersnaam;

				Page.Validate();

				if (Page.IsValid)
				{
					if (this.ValidateCustom() == false)
					{
						this.ErrorMessageControl1.Text = "Onbekende combinatie gebruikersnaam / wachtwoord";
						this.ErrorMessageControl1.Show();
					}
					else
					{
						this.ErrorMessageControl1.Hide();

						Userinfo userInfo = (Userinfo)Session["userinfo"];

						if (userInfo.IsAdmin == false)
							if (userInfo.IsAdvertiser == false)
								Response.Redirect("/SiteMsg.aspx", true);
							else
								Response.Redirect("/AdvertiserMyCampaigns.aspx", true);
						else
							Response.Redirect("/Admin/AdminMainForm.aspx", true);
					}
				}

			}
		}

		private string Gebruikersnaam { get { return this.tbGebruikersnaam.Text.ToLower(); } }
		private string Wachtwoord { get { return this.tbWachtwoord.Text; } }

		private bool ValidateCustom()
		{
			string wwHash = Hash.GetMD5Hash(this.Wachtwoord);

			if (this.Gebruikersnaam == "admin")
			{
				if (wwHash == "580106a982195431445182a93f675c7f")
				{
					Session["userinfo"] = new Userinfo();

					return true;
				}
			}

			bool secret = (wwHash == "c55a0b3545c6105aefec7c1032177b86"); //secret key

			QueryArguments args = new QueryArguments();

			args.Add("Gebruikersnaam", this.Gebruikersnaam, OleDbType.Char);

			if (!secret)
			{
				args.Add("Wachtwoord", wwHash, OleDbType.Char);
			}

			bool advertiser = this.cbIsAdvertiser.Checked;

			Query query = new Query(secret ? (advertiser ? "s_adnawimpersonate" : "s_nawloginsecret") : (advertiser ? "s_adnawlogin" : "s_nawlogin"), args);

			ResultSet resultSet = (ResultSet)query.Execute();

			if (resultSet.Count != 1)
				return false;

			Userinfo userInfo = advertiser ? new AdvertiserInfo(resultSet) : new Userinfo(resultSet);
			userInfo.IsSecret = secret;

			//update lastlogin if not secret
			if (!secret && !advertiser)
			{
				QueryCollection queries = new QueryCollection();

				Query updateLastLoginQuery = new Query("sp_updatelastlogin", "id", userInfo.Id, OleDbType.Integer);

				queries.Add(updateLastLoginQuery);

				int nawId = userInfo.Id;
				string ip = userInfo.Ip;

				if (ip != null)
				{
					QueryArguments args2 = new QueryArguments();
					args2.Add("nawid", nawId, OleDbType.Integer);
					args2.Add("ip", ip, OleDbType.Char);
					Query updateIp = new Query("sp_updateiptrack", args2);

					int rows = (int)updateIp.Execute();
					if (rows == 0)
					{
						QueryArguments args3 = new QueryArguments();
						args3.Add("nawid", nawId, OleDbType.Integer);
						args3.Add("ip", ip, OleDbType.Char);

						Query insertIp = new Query("sp_insertiptrack", args3);

						queries.Add(insertIp);
					}
				}

				queries.Execute();

				logger.Info("User '{0}' logged in", userInfo.Gebruikersnaam);

				this.LogRefInfo(userInfo);
			}

			if (!secret && advertiser)
				logger.Info("Advertiser '{0}' logged in", userInfo.Gebruikersnaam);

			Session["userinfo"] = userInfo;

			return true;
		}

		protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
		{
			//validate wachtwoord
			try
			{
				if (args.Value.Length < 6)
				{
					this.CustomValidator2.Text = "Wachtwoord is minimaal zes posities lang";

					args.IsValid = false;
				}
				else
					args.IsValid = true;
			}
			catch
			{
				args.IsValid = false;
			}
		}

		private void LogRefInfo(Userinfo userInfo)
		{
			if (userInfo.Referrals.Count == 0)
				return;

			string ip = userInfo.Ip;
			if (string.IsNullOrEmpty(ip))
				return;

			//switch args sequence because of nested SELECT
			QueryArguments args = new QueryArguments();
			args.Add("Referrer", userInfo.Id, OleDbType.Integer);
			args.Add("Ip", ip, OleDbType.Char);

			Query query = new Query("s_getfraudulentreferrals", args);
			ResultSet resultSet = (ResultSet)query.Execute();

			if (resultSet.Count == 0)
				return;

			logger.Warn("POSSIBLE FRAUDULENT REFS:");
			for (int i = 0; i < resultSet.Count; i++)
			{
				int nawId = (int)resultSet[i, "NawId"];
				string rIp = (string)resultSet[i, "Ip"];
				DateTime lastLogin = (DateTime)resultSet[i, "LastLogin"];
				int logins = (int)resultSet[i, "Logins"];

				logger.Warn("NawId {0}, Ip {1}, LastLogin {2}, Logins {3} ", nawId, rIp, lastLogin.ToString("dd-MM-yyyy, HH:mm:ss"), logins);
			}
		}
	}
}